﻿/*
The MIT License

Copyright (c) 2009 Gil Beyruth

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

*/

/**
 * 
 * UserList
 * Moving or modifying this file may affect the applications installed on this searver. 
 */

package com.firstpixel.multiuser{
	
	import flash.display.MovieClip;
	import flash.events.*;
	import flash.net.*;

	
	public class UserList extends MovieClip{
		var users_so:SharedObject;
		
		private var rtmp:String;
		private var username:String;
		private var gender:String;
		private var uid:Number;
						
		private var nc:NetConnection;
		private var users_so:SharedObject;			
		private var chat_so:SharedObject;
			
		[Bindable (ChangeEvent='histChange')]
		public var chatHistory:String = "";
			//[Bindable (ChangeEvent='dpChange')]
		public var dpUsers:ArrayCollection;
		
		public function UserList(){
			
		} 
		protected static var disp:EventDispatcher;
		
		public static function addEventListener(p_type:String, p_listener:Function, p_useCapture:Boolean=false, p_priority:int=0, p_useWeakReference:Boolean=false):void {
			if (disp == null) { disp = new EventDispatcher(); }
			disp.addEventListener(p_type, p_listener, p_useCapture, p_priority, p_useWeakReference);
		}
		public static function removeEventListener(p_type:String, p_listener:Function, p_useCapture:Boolean=false):void {
			if (disp == null) { return; }
			disp.removeEventListener(p_type, p_listener, p_useCapture);
		}
		public static function dispatchEvent(p_event:Event):void {
			if (disp == null) { return; }
			disp.dispatchEvent(p_event);
		}
		
  		// Public API that dispatches an event
  		public static function onConnectionSuccess():void {
   			dispatchEvent(new Event("onConnectionSuccess"));
   		}
		public static function connect(nc){
			this.nc = nc;
			users_so = SharedObject.getRemote("users", this.nc.uri, false);
			users_so.owner = this;
		}
					
			public function sendMsg( color:String, msg:String ):void
			{	
				var outmsg:String = "";			
				outmsg = "<font color='#" + color + "'><b>" + this.username+":</b> " + msg + "</font><br>";
				chat_so.send("onMsgSend", outmsg);
			}
			
			public function onUserid( uid:Number ):void
			{
				this.uid = uid;
				dispatchEvent( new UserIDEvent(UserIDEvent.USER_ID, uid));
			}
			
			private function netStatus( event:NetStatusEvent ):void
			{
				//trace("netStatus: " + event);
				var info:Object = event.info;				
	            switch(info.code)
	            {
	            	case "NetConnection.Connect.Success":      	
	            		users_so = SharedObject.getRemote("users_so", nc.uri, false);	            		      		
	            		users_so.addEventListener(SyncEvent.SYNC, usersSync);	            		  		
	            		users_so.addEventListener(NetStatusEvent.NET_STATUS, onSOnetStatus);	            			            		
						users_so.addEventListener(SecurityErrorEvent.SECURITY_ERROR, onSOSecurityError);
						users_so.client = this;
						users_so.connect(nc);	            		
	            		chat_so = SharedObject.getRemote("chat_so", nc.uri, false);	      
	            		chat_so.addEventListener(NetStatusEvent.NET_STATUS, onSOnetStatus);
	            		chat_so.addEventListener(SecurityErrorEvent.SECURITY_ERROR, onSOSecurityError);
	            		chat_so.client = this;
	            		chat_so.connect(nc);
	            	break;
	            	
	            	case "NetConnection.Connect.Closed":
						dispatchEvent( new NCEvent(NCEvent.STATUS, "closed"));
	            	break;
	            }
			}
			
			public function onMsgSend( msg:String ):void
			{
				trace("onMsgSend: " + msg);
				chatHistory += msg;		
				dispatchEvent(new Event("histChange"));
			}
						
			private function usersSync(event:SyncEvent):void
			{
				//trace("usersSync " + event.changeList);
				var results:Object = event.target.data;				
				var usersArray:Array = new Array();				
								
				for( var i:String in results )
				{
					var clientObj:UsersVO = new UsersVO();		
					clientObj.username = results[i].username;
					clientObj.status = results[i].status;
					clientObj.gender = results[i].gender;
					clientObj.uid = results[i].uid;
					clientObj.talking = results[i].talking;
					usersArray.push( clientObj );
					dpUsers = new ArrayCollection(usersArray);				
					dispatchEvent(new Event("dpChange"));
				}
			}
			
			private function netSecurityError(event:SecurityErrorEvent):void
			{
				trace("netSecurityError: " + event);
			}
			
			private function onSOnetStatus(event:NetStatusEvent):void
			{
				trace("onSOnetStatus: " + event);
			}
			
			private function onSOSecurityError(event:SecurityErrorEvent):void
			{
				trace("onSOSecurityError: " + event);
			}		
		
		
	}
}
	
/*
#initclip 1
//
function FCPeopleListClass() {
	this.init();
}
//
FCPeopleListClass.prototype = new MovieClip();
//
Object.registerClass("FCPeopleListSymbol", FCPeopleListClass);
//
FCPeopleListClass.prototype.init = function() {
	this.name = (this._name == null ? "_DEFAULT_" : this._name);
	this.prefix = "FCPeopleList." + this.name + ".";
};
//
FCPeopleListClass.prototype.onUnload = function() {
	this.close();
};

FCPeopleListClass.prototype.stripout = function(username) {
   this.statusList = new Array(" (player 1)"," (player 2)");
   this.statusLength = this.statusList.length;

   // loop through all statuses
   for(i=0; i<this.statusLength; i++) {
   // does username contain a status?
   var challenge = username.indexOf(this.statusList[i]);
   // yes it does
   if (challenge != -1) {
      // strip it
	  userArray = [];
      userArray[0] = username.split(this.statusList[i]).join("");
	  userArray[1] = this.statusList[i];
      return userArray;
      break;
	  }
   } return false;
}


//
FCPeopleListClass.prototype.connect = function(nc) {

	this.nc = nc;
	if (this.nc.FCPeopleList == null) {
		this.nc.FCPeopleList = {};
	}
	this.nc.FCPeopleList[this.name] = this;
	//
	this.so = SharedObject.getRemote(this.prefix + "users", this.nc.uri, false);
	this.so.owner = this;

	//
	this.so.onSync = function(list) {
		this.owner.people_lb.removeAll(this._width, this._height);
		var players = 0;
		var totalUsers = 0;
		var totalLurkers = 0;
		_root.play1_bt.gotoAndStop("join");
		_root.play2_bt.gotoAndStop("join");
		for (var i in this.data) {
			if (this.data[i] == " fc_lurker") {
				totalLurkers++;
			} else if (this.data[i] != null && this.data[i] != undefined){
				//&& this.data[i] != this.owner.username) {

				this.owner.userArray = [];
				this.owner.userArray = this.owner.stripout(this.data[i]);
				if(this.owner.userArray){					
					if(this.owner.userArray[1]==" (player 1)"){
						players++;
						_root.game.playerReady=players;
						_root.play1_bt.username = this.owner.userArray[0];
						_root.play1_bt.gotoAndStop("username");
					}else if(this.owner.userArray[1]==" (player 2)"){
						players++;
						_root.game.playerReady=players;
						_root.play2_bt.username = this.owner.userArray[0];
						_root.play2_bt.gotoAndStop("username");
					}
				}else{
					//_root.debug("spectator")
				}
				totalUsers++;
				//_root.debug("TOTALUSERS: "+totalUsers);
				this.owner.people_lb.addItem(this.data[i]);
			}
		}
		this.owner.lurkers = totalLurkers;
		this.owner.users = totalUsers;
		this.owner.people_lb.sortItemsBy("label", "ASC");
		//verifica se so tem 1 ou 0 jogadores
		if(players==0 || players==1){
			_root.debug("WAITING")
			_root.game.init=false;
			_root.game.reset();
			_root.controller_bt.gotoAndStop("wait");
		
		//se tiver dois jogadores verifica se init  partida para os spectators nao atrapalharem.
		} else if(players==2){
			_root.debug("GAME INIT"+_root.game.init);
			_root.debug("Game Status"+_root.game.status);
			if(_root.game.init!=true && _root.game.status!="spectator"){
				_root.debug("READY TO START")
				_root.controller_bt.gotoAndStop("start");
				_root.game.resetClock();
				_root.game.init=true;
			}
		} else {
			
		}
		if(!_root.userBipOff){
			var my_sound:Sound = new Sound();
			my_sound.attachSound("ring");
			my_sound.setVolume(20);
			my_sound.start();
		}
	};
	//
	this.so.connect(this.nc);
	// Need to call connect on our server side counterpart first
	this.nc.call(this.prefix + "connect", null);
};
//
FCPeopleListClass.prototype.close = function() {
	var fullName = "FCPeopleList." + this.name;
	// Let our server side counterpart know that we are going away
	this.nc.call(this.prefix + "close", null);
	//
	this.so.owner = null;
	delete this.so.owner;
	delete this.so.onSync;
	this.so.close();
	this.so = null;
	//
	this.nc.FCPeopleList[this.name] = null;
	this.nc = null;
};
//
FCPeopleListClass.prototype.setUsername = function (newName) {
	this.username = newName;
	this.nc.call(this.prefix + "changeName", null);
}
//
FCPeopleListClass.prototype.setSize = function (newWidth, newHeight) {
	this._xscale = 100;
	this._yscale = 100;
	this.people_lb.setSize(newWidth,newHeight);
}
//
#endinitclip
// B-)
this.setSize(this._width, this._height);

	
	*/
	